package handler

import (
	"strconv"

	"n-server/internal/model"
	"n-server/internal/model/dto"
	"n-server/internal/service"
	"n-server/pkg/common/errorcode"
	"n-server/pkg/common/request"
	"n-server/pkg/common/response"
	"n-server/pkg/logger"
	"n-server/pkg/utils/jwt"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

// UserHandler 定义用户处理器
type UserHandler struct {
	userService service.UserService
}

// NewUserHandler 创建 UserHandler 实例
func NewUserHandler(userService service.UserService) *UserHandler {
	return &UserHandler{userService: userService}
}

// @Summary 用户注册
// @Tags 用户模块
// @Router /user/register [post]
func (h *UserHandler) RegisterUser(c *gin.Context) {
	var req dto.RegisterUserRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, errorcode.PARAMS_ERROR)
		return
	}

	user, err := h.userService.RegisterUser(req.Username, req.Email, req.Password)
	if err != nil {
		logger.L().Error("Failed to register user", zap.Error(err), zap.String("username", req.Username))
		response.ErrorMsg(c, errorcode.OPREATION_ERROR, err.Error())
		return
	}

	response.Success(c, user)
}

// @Summary 用户登录
// @Tags 用户模块
// @Router /user/login [post]
func (h *UserHandler) LoginUser(c *gin.Context) {
	// 解析请求参数（用户名、密码）
	var req dto.LoginUserRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, errorcode.PARAMS_ERROR)
		return
	}

	// 调用服务层验证
	user, err := h.userService.LoginUser(req.Username, req.Password)
	if err != nil {
		logger.L().Error("Failed to login user", zap.Error(err), zap.String("username", req.Username))
		response.ErrorMsg(c, errorcode.OPREATION_ERROR, err.Error())
		return
	}

	// 生成 JWT Token
	token, err := jwt.GeneateToken(user.ID, user.Username, user.Role)
	if err != nil {
		response.Error(c, errorcode.OPREATION_ERROR)
	}

	// 返回 Token 和用户信息
	response.Success(c, gin.H{"token": token})
}

// @Summary 删除用户
// @Tags 用户模块
// @Router /user/delete [post] 
func (h *UserHandler) DeleteUser(c *gin.Context) {
	var req request.DeleteRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, errorcode.PARAMS_ERROR)
		return
	}

	if err := h.userService.DeleteUser(uint(req.ID)); err != nil {
		response.ErrorMsg(c, errorcode.OPREATION_ERROR, err.Error())
	}

	response.Success(c, "Delete user success")
}

// @Summary 更新用户
// @Tags 用户模块
// @Router /user/update [post]
func (h *UserHandler) UpdateUser(c *gin.Context) {
	var req dto.UpdateUserRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, errorcode.PARAMS_ERROR)
		return
	}

	if err := h.userService.UpdateUser(req.ID, &model.User{
		Username: req.Username,
		Email:    req.Email,
		Password: req.Password,
	}); err != nil {
		response.ErrorMsg(c, errorcode.OPREATION_ERROR, err.Error())
		return
	}

	response.Success(c, "Update user success")
}

// @Summary 分页查询用户列表
// @Tags 用户模块
// @Router /user/list [post]
func (h *UserHandler) ListUsers(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "10"))
	sort := c.DefaultQuery("sort", "id")
	order := c.DefaultQuery("order", "desc")

	if page < 1 {
		page = 1
	}

	if pageSize < 1 {
		pageSize = 10
	}

	// 验证排序
	if order != "asc" && order != "desc" {
		order = "desc"
	}

	user, total, err := h.userService.ListUsers(page, pageSize, sort, order)
	if err != nil {
		response.ErrorMsg(c, errorcode.OPREATION_ERROR, err.Error())
		return
	}

	response.SuccessWithPage(c, user, total, page, pageSize)

}

// @Summary 检测认证与授权功能请求
// @Tags 用户模块
// @Router /user/admin/demo [get]
func (h *UserHandler) AdminDemo(c *gin.Context) {
	data := "Welcome, Admin!"
	response.Success(c, data)
}
